package top.pro51.blog_admin.web;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import top.pro51.blog_admin.service.BlogService;
import top.pro51.blog_admin.service.TagService;
import top.pro51.blog_admin.service.TypeService;


@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    /**
     * @Description 首页博客信息展示
     * @Author WangWenpeng
     * @Date 15:12 2020/7/28
     * @Param [pageable, model]
     */
    @GetMapping("/")
    public String index(@PageableDefault(size = 8, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                        Model model) {
        model.addAttribute("page", blogService.listBlog(pageable));
        model.addAttribute("types", typeService.listTypeTop(6));
        model.addAttribute("tags", tagService.listTagTop(10));
        model.addAttribute("recommendBlogs", blogService.listRecommendBlogTop(8));
        return "index";
    }

    /**
     * @Description 右上角查询方法标题或者描述 不察 后续换Elasticsearch
     * @Author WangWenpeng
     * @Date 15:50 2020/7/28
     * @Param [pageable, query, model]
     */
    @PostMapping("/search")
    public String search(@PageableDefault(size = 8, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         @RequestParam String query, Model model) {
        //JPA用起来真麻烦 这种sql的like都这么费劲
        model.addAttribute("page", blogService.listBlog("%" + query + "%", pageable));
        model.addAttribute("query", query);
        return "search";
    }

    /**
     * @Description 跳转博客详情页面
     * @Author WangWenpeng
     * @Date 16:14 2020/7/28
     * @Param [id, model]
     */
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model) {
        model.addAttribute("blog", blogService.getAndConvert(id));
        return "blog";
    }

    //
    //@GetMapping("/footer/newblog")
    //public String newblogs(Model model) {
    //    model.addAttribute("newblogs", blogService.listRecommendBlogTop(3));
    //    return "_fragments :: newblogList";
    //}

}
